class Local {
    constructor() {
        this.game = new Game();
        this.timer = null;
        this.timeInterval = 200;
        this.timeCount = 0;
        this.time = 0;
    }
    //绑定键盘事件
    bindKeyEvent() {
        document.onkeydown = (e) => {//注意要用箭头函数
            if (e.keyCode == 38) {//up
                this.game.rotate();
            } else if (e.keyCode == 39) {//right
                this.game.right();
            } else if (e.keyCode == 40) {//down
                this.game.down();
            } else if (e.keyCode == 37) {//left
                this.game.left();
            } else if (e.keyCode == 32) {//space
                this.game.fall();
            }
        }
    }
    createLines(lineNum){
        let lines = [];
        for(let i=0;i<lineNum;i++){
            let line = [];
            for(let j=0;j<10;j++){       
                line.push(parseInt(Math.random()*2));
            }
            lines.push(line);
        }
        return lines;
    }
    createTimer() {
        this.timer = setInterval(() => {
            this.game.down();
            this.timeCount++;
            if(this.timeCount == 5){
                this.timeCount = 0;
                this.time += 1;
                this.game.setTime(this.time);
                if(this.time %5 == 0){
                    this.game.addTailLines(this.createLines(1));
                }
            }
            //console.log(this.game.down())
            if (!this.game.down()) {
                this.game.fixed();
               let line = this.game.checkClear();
               if(line){
                  this.game.addScore(line);
               }
                if (this.game.checkGameOver()) {
                    this.game.gameover(false);
                    this.stop();
                } else {
                    this.game.performNext();//使用下一个方块
                }
            }
        }, this.timeInterval);
    }

    start() {
        this.game.init();
        this.bindKeyEvent();
        this.createTimer();
    }

    stop(){
        if(this.timer){
            clearInterval(this.timer);
            this.timer = null;
        }
        document.onkeydown = null;
    }
}